<?php

namespace Org\SueCrypt;

/**
 * SuStrSerialize 类
 *
 * @since VER:1.0; DATE:2016-4-26; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class SueSerial {

    /**
     * 字符串序列化
     * @param string $str 字符串
     * @param int $count 序列组数量
     * @param char $splitor 序列分隔符
     * @return string
     * @since 1.0 <2015-7-9> SoChishun Added.
     */
    private static function str_serial($str, $count, $splitor = '-') {
        $len = strlen($str);
        $n = ceil($len / $count);
        return wordwrap($str, $n, $splitor, true);
    }

    /**
     * 字符串混淆加密并串行化
     * 用于生成授权序列号,支持中文、英文、数值、符号
     * @param string|array $data 原文
     * @param string $key 混淆密匙
     * @param int $count 序列号组数量
     * @param char $splitor 序列号分隔符
     * @return string 混淆加密后的密文,密文可能包含符号(%#*.)
     * @since 1.0 <2015-7-9> SoChishun Added.
     * @example str_encserial(array('status' => true, 'co.' => '鑫优祥.lnc', 'sn' => 'pwd!@#$%^&*_+<?[}密匙', 'url' => 'http://www.abc.com', 'date' => '2015-7-9 13:23:30 星期四', 'author' => '天澜<14507247@qq.com>')) => tYYgn64sEZR9SfQhkZJBkRa2UyOsz%%hxdW6c9k#9m*ce70mg*16JzKNo-WwnZ5zCfRqmbN04qXAIf.Ib6nAEfHg3Wa#uQJRHioC0z%ARW8#yAAXjo7-M4SK#IpnVc7Lh4wkeVXC.sFoqmI.kmkQh%9xzNtB#nHH6coKBRuqdc1NQ-iq1n29vR3LZiHOcd5wKcDyLDSav9eLJzXmje4XzdkZhGPsIv7mpcHVph9-Vv%HXt4HoFAFUQJAzsbQVLkp%..euSzxeXqGSVNeIExADWA#hmVp%
     */
    public static function encrypt($data, $key = 'Sue123!@#', $count = 5, $splitor = '-') {
        $str = is_array($data) ? json_encode($data) : $data;
        $str = SueDes::encrypt($str, $key); // Des加密
        $mix = SueStrmix::encrypt($str); // 混淆
        if ($splitor) {
            $mix = self::str_serial($mix, $count, $splitor); // 串列
        }
        return $mix;
    }

    /**
     * 字符串反混淆加密串行化
     * @param string $str 密文
     * @param string $key 混淆密匙
     * @param char $splitor 序列号分隔符
     * @param boolean $parse_array 是否转换为Array
     * @return string|Array
     * @since 1.0 <2015-7-9> SoChishun Added.
     * @example str_dencserial('tYYgn64sEZR9SfQhkZJBkRa2UyOsz%%hxdW6c9k#9m*ce70mg*16JzKNo-WwnZ5zCfRqmbN04qXAIf.Ib6nAEfHg3Wa#uQJRHioC0z%ARW8#yAAXjo7-M4SK#IpnVc7Lh4wkeVXC.sFoqmI.kmkQh%9xzNtB#nHH6coKBRuqdc1NQ-iq1n29vR3LZiHOcd5wKcDyLDSav9eLJzXmje4XzdkZhGPsIv7mpcHVph9-Vv%HXt4HoFAFUQJAzsbQVLkp%..euSzxeXqGSVNeIExADWA#hmVp%') => {"status":true,"co.":"\u946b\u4f18\u7965.lnc.co","sn":"pwd!@#$%^&*()_+<>?{}[]\u5bc6\u5319","url":"http:\/\/www.abc.com","date":"2015-7-9 13:23:30 \u661f\u671f\u56db","author":"\u5929\u6f9c<14507247@qq.com>"}
     */
    public static function decrypt($str, $key = 'Sue123!@#', $splitor = '-', $parse_array = false) {
        $str = str_replace('-', '', $str); // 反串列
        $org = SueStrmix::decrypt($str); // 反混淆
        $str = SueDes::decrypt($org, $key); // 反Des加密
        return $parse_array ? (Array) json_decode($str) : $str;
    }

}
